/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.arg.deploy.common;

import com.arg.deploy.bean.Tag;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Set;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;

/**
 *
 * @author puchongi
 */
public class GenScript {

    private static final Logger LOG = Logger.getLogger(GenScript.class);
    public static final String TAG_TYPE_VERSION_CONTROL = "1";
    public static final String TAG_TYPE_NORMAL = "2";
    private final String tagName;
    private final String cvsName;
    private final String inputFile;
    private final String outputFile;
    private List<Tag> tag;

    public GenScript(String tagName, String cvsName, String inputFile, String outputFile) {
        this.tagName = tagName;
        this.cvsName = cvsName;
        this.inputFile = inputFile;
        this.outputFile = outputFile;
    }

    public List<Tag> getListTagObject() {
        if (tag == null) {
            tag = new ArrayList<Tag>();
        }
        return this.tag;
    }

    public static List<Tag> generate(String inputFile) {

        List<Tag> tagObject = new ArrayList<Tag>();

        try {
            BufferedReader br = new BufferedReader(new FileReader(inputFile));
            String line = null;
            while ((line = br.readLine()) != null) {
                String[] split = line.trim().split("Rev.");
                Tag tag = new Tag();
                List<String> tagString = new ArrayList<String>();
                for (String s : split) {
                    if (!StringUtils.isEmpty(s.trim())) {
                        System.out.println("::::::::::: s.trim() = " + s.trim());
                        tagString.add(s.trim());
                    }
                }

                System.out.println("::::::::::::::::: tagString.size() = " + tagString.size());

                String[] mode = tagString.get(0).split("\t");
                String[] version = tagString.get(1).split(" ");
                tag.setMode(mode[0]);
                tag.setPath(mode[mode.length - 1]);

                String[] filename = mode[mode.length - 1].split("/");
                tag.setFilename(filename[filename.length - 1]);

                tag.setRevision(version[0]);
                tagObject.add(tag);
            }

            br.close();
        } catch (Exception e) {
            LOG.error(e.getMessage(), e);
        }

        return tagObject;
    }

    public static List<Tag> generate(String tagText, String tagType, String header) {
        List<Tag> tagObject = new ArrayList<Tag>();
        try {
            if (tagType.equals(TAG_TYPE_VERSION_CONTROL)) {
                String[] text = tagText.split("\n");
                for (String line : text) {
                    if (StringUtils.isEmpty(line.trim())) {
                        continue;
                    }
                    String[] split = line.trim().split("Rev.");
                    Tag tag = new Tag();
                    List<String> tagString = new ArrayList<String>();
                    for (String s : split) {
                        if (!StringUtils.isEmpty(s.trim())) {
                            System.out.println("::::::::::: s.trim() = " + s.trim());
                            tagString.add(s.trim());
                        }
                    }
                    System.out.println("::::::::::::::::: tagString.size() = " + tagString.size());

                    String[] mode = tagString.get(0).split("\t");
                    String[] version = tagString.get(1).split(" ");
                    tag.setMode(mode[0].trim());
                    tag.setPath(mode[mode.length - 1].trim());

                    String[] filename = mode[mode.length - 1].split("/");
                    tag.setFilename(filename[filename.length - 1].trim());

                    tag.setRevision(version[0].trim());
                    tagObject.add(tag);
                }
            } else if (tagType.equals(TAG_TYPE_NORMAL)) {
                String[] text = tagText.split("\n");
                for (String line : text) {
                    if (StringUtils.isEmpty(line.trim())) {
                        continue;
                    }
                    String[] split = line.trim().split(",");
                    Tag tag = new Tag();
                    if (split.length == 1) {
                        tag.setMode("MODIFY");
                        tag.setPath(split[0].trim());

                        String[] filename = split[0].split("/");
                        tag.setFilename(filename[filename.length - 1].trim());
                        
                        StringBuilder sb = new StringBuilder();
                        sb.append("cvs -d :pserver:").append(GenerateScriptUtil.CVS_USER).append("@").append(GenerateScriptUtil.IP_CVS_SERVER_PATH).append(" co ").append(tag.getPath());
                        sb.append("\n");
                        sb.append("cvs -d :pserver:").append(GenerateScriptUtil.CVS_USER).append("@").append(GenerateScriptUtil.IP_CVS_SERVER_PATH).append(" log ").append(tag.getPath());
                        LOG.info(":::::::::::::::::::::::: sb = " + sb.toString());
                        ProcessUbuntu process = new ProcessUbuntu(header, sb);
                        process.process("chmod 777 " + header + "/" + ProcessUbuntu.TEMP_SCRIPT_FILENAME);
                        process.process();

                        if (!StringUtils.isEmpty(process.getErrorString())) {
                            throw new NullPointerException();
                        } else {
                            String[] logTag = process.getOutputString().split("\n");
                            Boolean isSuccess = validateTag(logTag, tag);

                            if (!isSuccess) {
                                throw new NullPointerException();
                            }
                        }
                    } else if (split.length == 2) {
                        tag.setMode("MODIFY");
                        tag.setPath(split[0].trim());

                        String[] filename = split[0].split("/");
                        tag.setFilename(filename[filename.length - 1].trim());

                        tag.setRevision(split[1].trim());
                    } else if (split.length == 3) {
                        tag.setMode(split[0].trim());
                        tag.setPath(split[1].trim());

                        String[] filename = split[1].split("/");
                        tag.setFilename(filename[filename.length - 1].trim());

                        tag.setRevision(split[2].trim());
                    }
                    tagObject.add(tag);
                }
            }
        } catch (Exception e) {
            LOG.error(e.getMessage(), e);
        }
        return tagObject;
    }

    private static Boolean validateTag(String[] tag,
            Tag tagObject) throws UnsupportedEncodingException {

        if (tag == null) {
            return Boolean.FALSE;
        }

        String revision = null;
        for (String s : tag) {
            if (s.length() > 10) {
                if (revision != null) {
                    break;
                }
                if (s.substring(0, 8).equals("revision")
                        && revision == null) {
                    String revisionTemp = s.substring(9, s.length());
                    if (revisionTemp.replace(".", ",").split(",").length == 4) {
                        revision = revisionTemp;
                    }
                }
            }
        }
        LOG.info("::::::::::::: revision = " + revision);

        if (revision == null) {
            return Boolean.FALSE;
        }

        revision = revision.trim();
        tagObject.setRevision(revision);

        return Boolean.TRUE;
    }

    public void GenerateScript() throws FileNotFoundException, IOException {

        BufferedReader br = new BufferedReader(new FileReader(inputFile));
        String line = null;
        HashMap map = new HashMap();
        while ((line = br.readLine()) != null) {
//            System.out.println(line);
            line = line.replace("MODIFY	", "d1/ccs/");
            LOG.info("::::::::::::::::::: line = " + line);
            line = line.replace("Rev.", "Revision");
            LOG.info("::::::::::::::::::: line = " + line);
            String[] temp = line.split("Revision");
            if (temp != null && temp.length > 1) {
                temp[0] = temp[0].trim();
                temp[1] = temp[1].trim();
                LOG.info("::::::::::::::::::: temp[0] = " + temp[0]);
                String[] tmp = temp[1].split("	 	");
                if (tmp != null && tmp.length >= 1) {
                    if (!map.containsKey(temp[0])) {
                        map.put(temp[0].trim(), tmp[0].trim());
                    } else {
                        String revision = (String) map.get(temp[0]);
                        LOG.info("::::::::::::::::::: temp[0] = " + temp[0]);
                        String t = revision.replace(".", ",");
                        String split = tmp[0].replace(".", ",");
                        LOG.info("::::::::::::::::::: t = " + t);
                        LOG.info("::::::::::::::::::: split = " + split);
                        String[] re = t.split(",");
                        String[] reNew = split.split(",");
                        LOG.info("::::::::::::::::::: re[3] = " + re[3]);
                        LOG.info("::::::::::::::::::: reNew[3] = " + reNew[3]);
                        String revis = re[3].trim();
                        String revisionNew = reNew[3].trim();
                        if (Integer.valueOf(revis).intValue() < Integer.valueOf(revisionNew).intValue()) {
                            map.put(temp[0], tmp[0]);
                        }
                    }
                }
            }
        }
        List<String> key = new ArrayList<String>();
        Set<String> st = map.keySet();
        key.addAll(st);
        LOG.info("::::::::::::::::::: List File = " + key.size());
        for (String k : key) {
            LOG.info("::::::::::::::::::: k = " + k);
            LOG.info("::::::::::::::::::: map.get(k) = " + map.get(k));
        }

        BufferedWriter writer = null;
        try {
            //create a temporary file
            File logFile = new File(outputFile);
            // This will output the full path where the file will be written to...

            writer = new BufferedWriter(new FileWriter(logFile, false));

            tag = new ArrayList<Tag>();

            for (String keyName : key) {
                LOG.info("::::::::::::::::::: keyName = " + keyName);
                LOG.info("::::::::::::::::::: map.get(keyName) = " + map.get(keyName));
                String writeToFile = null;
                if (map.containsKey(keyName)) {
                    writeToFile = "cvs -d :pserver:" + cvsName + "@172.21.44.206/usr/local/arg" + " tag -r " + map.get(keyName) + " -F " + tagName + " " + keyName + "\n";
                    LOG.info("::::::::::::::::::: writeToFile = " + writeToFile);

                    Tag object = new Tag();
                    object.setPath(keyName);
                    String[] name = keyName.split("/");
                    object.setFilename(name[name.length - 1]);
                    tag.add(object);

                    writer.write(writeToFile);
                }

            }

        } catch (Exception e) {
            LOG.error(e.getMessage(), e);
            e.printStackTrace();
        } finally {
            try {
                // Close the writer regardless of what happens...
                writer.close();
            } catch (Exception e) {
                LOG.error(e.getMessage(), e);
            }
        }
    }
}
